import React, { useState, useEffect } from 'react';
import { Card, Empty, message, Typography, Tag, Spin } from 'antd';
import { useNavigate } from 'react-router-dom';
import { Team } from '@/types/account';
import { ProblemSet } from '@/types/problemSet';
import { problemSetService } from '@/services/problemSetService';
import styles from '../index.module.css';

const { Title, Text } = Typography;

interface ProblemSetComponentProps {
  currentTeam: Team | null;
  problemSetType: 'team' | 'public';
  onCountChange?: (count: number) => void; // 可选的回调函数，用于回传题单数量
}

/**
 * 题单组件，只负责获取和显示指定类型的题单
 */
const ProblemSetComponent: React.FC<ProblemSetComponentProps> = ({ 
  currentTeam, 
  problemSetType,
  onCountChange 
}) => {
  const navigate = useNavigate();
  const [problemSets, setProblemSets] = useState<ProblemSet[]>([]);
  const [loading, setLoading] = useState(false);

  // 获取题单列表
  useEffect(() => {
    fetchProblemSets();
  }, [currentTeam, problemSetType]);

  const fetchProblemSets = async () => {
    setLoading(true);
    try {
      let response;
      
      if (problemSetType === 'team' && currentTeam) {
        // 获取团队题单
        response = await problemSetService.getProblemSets({
          team_id: currentTeam.id,
          page: 1,
          limit: 100,
        });
      } else {
        // 获取公开题单
        response = await problemSetService.getProblemSets({
          page: 1,
          limit: 100,
        });
      }
      
      if (response.data && response.data.data && response.data.data.results) {
        // 过滤激活的题单
        const activeProblemSets = response.data.data.results.filter(
          (problemSet: ProblemSet) => problemSet.is_active
        );
        setProblemSets(activeProblemSets);
        // 回传题单数量
        onCountChange?.(activeProblemSets.length);
      }
    } catch (error) {
      console.error('获取题单列表失败:', error);
      message.error('获取题单列表失败');
      // 错误时也要回传0
      onCountChange?.(0);
    } finally {
      setLoading(false);
    }
  };

  const handleViewProblemSet = (problemSet: ProblemSet) => {
    navigate(`/practice/problem-set/${problemSet.id}`);
  };

  const renderProblemSetCard = (problemSet: ProblemSet) => (
    <Card
      key={problemSet.id}
      className={styles.problemSetCard}
      hoverable
      onClick={() => handleViewProblemSet(problemSet)}
    >
      <div className={styles.problemSetHeader}>
        <Title level={4} className={styles.problemSetTitle}>
          {problemSet.title}
        </Title>
        <Tag color={problemSetType === 'team' ? "blue" : "green"}>
          {problemSetType === 'team' ? "团队" : "公开"}
        </Tag>
      </div>
      
      <Text type="secondary" className={styles.problemSetDescription}>
        {problemSet.description || '暂无描述'}
      </Text>
      
      <div className={styles.problemSetFooter}>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          题目数量: {problemSet.problem_count || 0}
        </Text>
        <Text type="secondary" style={{ fontSize: '12px' }}>
          创建时间: {new Date(problemSet.created_time).toLocaleDateString()}
        </Text>
      </div>
    </Card>
  );

  if (loading) {
    return (
      <div className={styles.loadingContainer}>
        <div className={styles.loading}>加载中...</div>
      </div>
    );
  }

  return (
    <div>
      {problemSets.length === 0 ? (
        <Empty
          description={problemSetType === 'team' ? "该团队暂无题单" : "暂无公开题单"}
          image={Empty.PRESENTED_IMAGE_SIMPLE}
        />
      ) : (
        <div className={styles.problemSetGrid}>
          {problemSets.map((problemSet: ProblemSet) => 
            renderProblemSetCard(problemSet)
          )}
        </div>
      )}
    </div>
  );
};

export default ProblemSetComponent;
